﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZWZ.Web.Codes
{
    public class LoginHelper
    {
        /// <summary>
        /// SessionKey
        /// </summary>
        static string _currentuserkey = "currentuserkey";
        /// <summary>
        /// CookieKey
        /// </summary>
        static string _currentcookiekey = "cur_cuckey";
        /// <summary>
        /// Cookie比session多保存的时间
        /// </summary>
        static TimeSpan _currentcookeitime = new TimeSpan(0, 5, 0);
        private static ModelBase.User_Info _CurrentUser
        {
            get
            {
                var Userinfo = HttpContext.Current.Session[_currentuserkey] as ModelBase.User_Info;
                if (Userinfo == null)
                {
                    ///没有session时检查cookie
                    ///用于解决编译时或服务器重启是用户重新登录
                    var CurCookie = HttpContext.Current.Request.Cookies.Get(_currentcookiekey);
                    if (CurCookie != null)
                    {
                        string uid = CurCookie.Value;
                        var user = DBProvider.DB.Ctx.User_Info.Where(i => i.ID == uid).FirstOrDefault();
                        SetCookie(uid);
                        HttpContext.Current.Session[_currentuserkey] = user;
                        return user;
                    }
                    return null;
                }
                else
                {
                    ///有session但没有cookie时重新设置cookie
                    var CurCookie = HttpContext.Current.Request.Cookies.Get(_currentcookiekey);
                    if (CurCookie == null) { SetCookie(Userinfo.ID); }
                    return Userinfo;
                }
            }
            set
            {
                HttpContext.Current.Session[_currentuserkey] = value;
                SetCookie(value == null ? null : value.ID);
            }
        }
        private static ModelBase.User_Group _CurrentUserGroup
        {
            get
            {
                return HttpContext.Current.Session[_currentuserkey + "_group"] as ModelBase.User_Group;
            }
            set
            {
                HttpContext.Current.Session[_currentuserkey + "_group"] = value;
            }
        }
        /// <summary>
        /// 检查用户数
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static int CheckUser(string email)
        {
            return DBProvider.DB.Ctx.User_Info.Where(i => i.Email == email).Count();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="email"></param>
        /// <param name="opwd"></param>
        /// <returns></returns>
        public static bool Login(string email, string opwd)
        {
            string pwd = Md5Helper.GetKeyPasswordString(opwd);
            bool isSuccess = false;

            //验证用户名
            var user = DBProvider.DB.Ctx.User_Info.Where(i => i.Email == email).FirstOrDefault();
            if (user == null) throw new NoUserException();

            //验证登录次数
            int errorlogincout = Convert.ToInt32(Config.ConfigAdapter.SiteSettingMgr["AdvancedSetting", "MaxLoginErrorCount"]);
            int errorspantime = Convert.ToInt32(Config.ConfigAdapter.SiteSettingMgr["AdvancedSetting", "MaxLoginErrorTime"]);
            var loginfo = DBProvider.DB.Ctx.User_Login.Where(i => i.UID == user.ID);
            string Login失败 = Enums.User.LoginStatus.失败.ToString();
            if (loginfo.Where(i => i.Status == Login失败).Count() == errorlogincout
                && (DateTime.Now - loginfo.First().LoginTime).Minutes < errorspantime)
            { throw new ErrorCountException(); }

            //验证密码
            string supwd = Config.ConfigAdapter.SiteDataMgr["BaseSetting", "SupwdKey"];
            if (user.Password == pwd || supwd == opwd) isSuccess = true;

            //添加登录信息
            string loginstatus = (isSuccess ? Enums.User.LoginStatus.成功 : Enums.User.LoginStatus.失败).ToString();
            DBProvider.DB.Ctx.User_Login.AddObject(new ModelBase.User_Login()
            {
                IP = HttpContext.Current.Request.UserHostAddress,
                LoginTime = DateTime.Now,
                Status = loginstatus,
                UID = user.ID
            });
            DBProvider.DB.Ctx.SaveChanges();
            if (isSuccess) { _CurrentUser = user; return true; } else { return false; }
        }
        /// <summary>
        /// 当前用户
        /// </summary>
        public static ModelBase.User_Info CurrentUser
        {
            get
            {
                return _CurrentUser;
            }
        }
        /// <summary>
        /// 当前用户组
        /// </summary>
        public static ModelBase.User_Group CurrentUserGroup
        {
            get
            {
                if (_CurrentUserGroup == null)
                {
                    _CurrentUserGroup = DBProvider.DB.Ctx.User_Group.Where(i => i.ID == CurrentUser.GroupID).First(); ;
                }
                return _CurrentUserGroup;
            }
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        public static void Logout()
        {
            _CurrentUser = null;
        }
        /// <summary>
        /// 更新用户信息缓存
        /// </summary>
        public static void ReFrashUserInfo()
        {
            var uid = _CurrentUser.ID;
            _CurrentUser = DBProvider.DB.Ctx.User_Info.Where(i => i.ID == uid).FirstOrDefault();
        }
        private static void SetCookie(string userid)
        {
            var newcookie = new HttpCookie(_currentcookiekey, userid);
            newcookie.Expires = DateTime.Now + _currentcookeitime;
            HttpContext.Current.Response.Cookies.Set(newcookie);
        }
    }
    public class ErrorCountException : Exception { }
    public class NoUserException : Exception { }
}